package com.pay.cloud.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.pay.cloud.DataFactory;
import com.pay.cloud.KeyInfo;
import com.pay.cloud.KeyInfoListener;
import com.pay.cloud.PwdValidator;
import com.pay.cloud.PwdCheckerDefault;
import com.pay.cloud.R;
import com.pay.cloud.StatusListener;
import com.pay.cloud.fragment.PwdInputFragment.OnPwdListener;


public class PasswordFragment extends AbstractFragment implements KeyInfoListener, OnPwdListener {
    private PwdInputFragment pwdInput = new PwdInputFragment();
    private StatusListener listener;
    private boolean isValidOldPwd = false;
    private TextView labelView;
    private String newPwd;
    public PasswordFragment(StatusListener listener) {
        this.listener = listener;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_password, container, false);

        pwdInput.setOnPwdListener(this);

        labelView = view.findViewById(R.id.pwd_input_label);
        labelView.setText(R.string.pwd_type_in_old);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.password_main_container, pwdInput);
        fragmentTransaction.commit();

        return view;
    }

    @Override
    public boolean onKeyDown(KeyInfo keyInfo) {
        return pwdInput.onKeyDown(keyInfo);
    }

    @Override
    public void finish(String pwd) {
        if (!isValidOldPwd) {
            PwdValidator checker = new PwdCheckerDefault();
            if (checker.isValid(pwd)) {
                isValidOldPwd = true;
                labelView.setText(R.string.pwd_type_in_new);
            } else {
                showToast(getString(R.string.pwd_old_incorrect));
                labelView.setText(R.string.pwd_type_in_old);
            }
            clearInput();
        } else if (null == newPwd) {
            newPwd = pwd;
            labelView.setText(R.string.pwd_type_in_twice);
            clearInput();
        } else {
            if (!pwd.equals(newPwd)) {
                showToast(getString(R.string.pwd_twice_incorrect));
                newPwd = null;
                labelView.setText(R.string.pwd_type_in_new);
                clearInput();
            } else {
                DataFactory.getDataStore().setPwd(pwd);
                //showToast("密码修改成功");
                listener.onSuccess(getString(R.string.pwd_set_success));
            }
        }
    }

    private void clearInput() {
        handleDelay(pwdInput::clear, 300);
    }

}
